import React, { useState } from 'react';

interface CollapsibleSectionProps {
  title: string;
  children: React.ReactNode;
  defaultOpen?: boolean;
  titleClassName?: string;
  headerContent?: React.ReactNode; // Optional content to display next to the title
}

const ChevronDownIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor" {...props}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
  </svg>
);

const CollapsibleSection: React.FC<CollapsibleSectionProps> = ({
  title,
  children,
  defaultOpen = false,
  titleClassName = "text-lg font-semibold",
  headerContent,
}) => {
  const [isOpen, setIsOpen] = useState(defaultOpen);

  const toggleOpen = () => setIsOpen(!isOpen);

  return (
    <div className="border-b border-gray-700 last:border-b-0 py-2">
      <div
        className="flex justify-between items-center cursor-pointer select-none"
        onClick={toggleOpen}
        aria-expanded={isOpen}
        aria-controls={`collapsible-content-${title}`}
      >
        <h3 className={`${titleClassName} text-gray-200`}>{title}</h3>
        <div className="flex items-center space-x-2">
            {headerContent && <div onClick={(e) => e.stopPropagation()}>{headerContent}</div>}
            <ChevronDownIcon
            className={`w-5 h-5 text-gray-400 transform transition-transform duration-200 ${
                isOpen ? 'rotate-180' : 'rotate-0'
            }`}
            />
        </div>
      </div>
      <div
        id={`collapsible-content-${title}`}
        className={`grid transition-[grid-template-rows] duration-300 ease-in-out ${
          isOpen ? 'grid-rows-[1fr]' : 'grid-rows-[0fr]'
        }`}
      >
        <div className="overflow-hidden">
          <div className="pt-2">
            {children}
          </div>
        </div>
      </div>
    </div>
  );
};

export default CollapsibleSection;
